package com.atguigu.gulimall.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.service.ISendCodeService;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/9 14:03 周一
 * @description :
 */
@Service
@AllArgsConstructor
public class SendCodeServiceImpl implements ISendCodeService {

    private final ThirdPartFeignService thirdPartFeignService;

    private final StringRedisTemplate redisTemplate;

    @Override
    public R sendCode(String phone) {

        // TODO 1. 接口防刷

        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

        // 2. 验证码的再次校验 redis中存储
        String redisCode = opsForValue.get(key);
        if (Func.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < AuthServerConstant.SIX_TIME) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String codeInt = String.valueOf(Math.abs(RandomUtil.randomInt()));

        String code = codeInt + "_" + System.currentTimeMillis();
        // redis缓存验证码 防止同一个phone在60秒内再次发送验证码
        opsForValue.set(key, code, Duration.ofMinutes(10));
        thirdPartFeignService.sendCode(phone, codeInt);
        return R.ok();
    }

}
